package com.substation.ui.activity;

import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.greenentity.Ready;
import com.greenentity.SafetyTool;
import com.greenentity.Substation;
import com.greenentity.Task;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.substation.R;
import com.substation.greendao.ReadyDao;
import com.substation.greendao.SafetyToolDao;
import com.substation.greendao.SubstationDao;
import com.substation.ui.utils.RecyclerViewUtils;
import com.substation.utils.DateUtils;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.SPUtils;
import com.substation.utils.T;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 巡视前准备工作
 */
public class ReadyActivity extends BaseActivity {

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.readCount)
    TextView readCount;
    @BindView(R.id.readList)
    RecyclerView readList;
    @BindView(R.id.toolList)
    RecyclerView toolList;
    List<Ready> readies = new ArrayList<>();
    List<SafetyTool> safetyTools = new ArrayList<>();
    SuperAdapter<Ready> readyAdapter;
    SuperAdapter<SafetyTool> toolAdapter;
    int readyCount = 0, totalCount = 0;
    Task task;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_safety;
    }

    @Override
    protected void initView() {
        String taskContent = (String) SPUtils.get(context, "task", "");
        task = JSON.parseObject(taskContent, Task.class);
        readList.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        toolList.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        toolList.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        readList.setAdapter(readyAdapter = new SuperAdapter<Ready>(R.layout.content_ready) {
            @Override
            public void bindView(ViewHolder viewHolder, final Ready ready, int i) {
                ((TextView) viewHolder.getView(R.id.dangerContent)).setText(ready.getDanger());
                ((TextView) viewHolder.getView(R.id.title)).setText(ready.getAttentionTypevalue());
                ((TextView) viewHolder.getView(R.id.safetyContent)).setText(ready.getSafety().replaceAll("</br>","\n"));
                final Button see = viewHolder.getView(R.id.see);
                see.setText("确认");
                see.setClickable(true);
                see.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ready.setConfirmFlag("1");
                        ready.setConfirmFlagvalue("是");
                        ready.setConfirmTime(DateUtils.getNewTime());
                        GreenDaoManager.getInstance().getmDaoSession().getReadyDao().update(ready);
                        readyCount++;
                        setSafety();
                        see.setText("已确认");
                        see.setClickable(false);
                    }
                });
                if (ready.getConfirmFlag() != null && !ready.getConfirmFlag().equals("")) {
                    if (ready.getConfirmFlag().equals("1")) {
                        see.setText("已确认");
                        see.setClickable(false);
                    }
                }
            }
        });
        readyAdapter.setData(readies);
        toolList.setAdapter(toolAdapter = new SuperAdapter<SafetyTool>(R.layout.content_safetytool) {
            @Override
            public void bindView(ViewHolder viewHolder, final SafetyTool safetyTool, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(safetyTool.getToolsName());
                ((TextView) viewHolder.getView(R.id.type)).setText(safetyTool.getToolsType());
                ((TextView) viewHolder.getView(R.id.unit)).setText(safetyTool.getToolsUnit());
                final EditText editText = viewHolder.getView(R.id.count);
                editText.setText((int)safetyTool.getToolsNum() + "");
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        if(TextUtils.isEmpty(editable.toString())){
                            safetyTool.setToolsNum(0);
                        }else{
                            safetyTool.setToolsNum(Double.parseDouble(editable.toString()));
                        }
                        GreenDaoManager.getInstance().getmDaoSession().getSafetyToolDao().update(safetyTool);
                    }
                });
            }
        });
        toolAdapter.setData(safetyTools);
    }

    @Override
    protected void initData() {
        readies.clear();
        safetyTools.clear();
        String workGuid = task.getWorkGuid();
        String subGuid = task.getSubsGuid();
        String workType = task.getTourTypevalue();
        readies.addAll(GreenDaoManager.getInstance().getmDaoSession().getReadyDao().queryBuilder().where(ReadyDao.Properties.WorkGuid.eq(workGuid)).list());
        readyAdapter.notifyDataSetChanged();
        totalCount = readies.size();
        readyCount = (int) GreenDaoManager.getInstance().getmDaoSession().getReadyDao().queryBuilder().where(ReadyDao.Properties.WorkGuid.eq(workGuid), ReadyDao.Properties.ConfirmFlag.eq("1")).count();
        readCount.setText("(" + readyCount + "/" + totalCount + ")");
        List<Substation> substations = GreenDaoManager.getInstance().getmDaoSession().getSubstationDao().queryBuilder().where(SubstationDao.Properties.Guid.eq(subGuid)).list();
        name.setText((substations.size() > 0 ? substations.get(0).getNames() : "未知变电站") + workType);
        safetyTools.addAll(GreenDaoManager.getInstance().getmDaoSession().getSafetyToolDao().queryBuilder().where(SafetyToolDao.Properties.WorkGuid.eq(workGuid)).list());
        toolAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.continu, R.id.seeAll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.continu:
                if (readyCount < totalCount) {
                    showMsg("您还有未确认的安全须知");
                    return;
                }
                setSafety();
                startActivity(new Intent(context, PatrolActivity.class));
                finish();
                break;
            case R.id.seeAll:
                for (Ready ready : readies) {
                    if (ready.getConfirmFlag().equals("0")) {
                        ready.setConfirmFlag("1");
                        ready.setConfirmFlagvalue("是");
                        ready.setConfirmTime(DateUtils.getNewTime());
                        GreenDaoManager.getInstance().getmDaoSession().getReadyDao().update(ready);
                        readyCount++;
                    }
                }
                setSafety();
                readyAdapter.notifyDataSetChanged();
                T.showLong(context, "已确认");
                break;
        }
    }

    void setSafety() {
        if (readyCount == totalCount) {
            task.setSafety(1);
            SPUtils.put(context, "task", JSON.toJSONString(task));
            GreenDaoManager.getInstance().getmDaoSession().getTaskDao().update(task);
        }
        readCount.setText("(" + readyCount + "/" + totalCount + ")");
    }
}
